package com.amazon.web.util;

import com.amazon.bo.Product;
import com.amazon.bo.Shop;
import com.amazon.bo.ShopClass;
import com.amazon.dao.EanDao;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;

public class SignatureUtil {
    public static final String CHARACTER_ENCODING = "UTF-8";
    public static String ALGORITHM = "HmacSHA256";
    public static final String SERVICE_URL="https://mws.amazonservices.co.uk/";



    public static String getOrder(Shop shop) throws Exception {
        // Change this secret key to yours
        String secretKey = shop.getSecretKey()==null?"ys/XvaP+LxVS7vXtzWnaS2CRYqmIG3HIgkMKBaBs":shop.getSecretKey();

        // Use the endpoint for your marketplace
        String serviceUrl =shop.getServiceUrl()==null? "https://mws.amazonservices.co.uk/":shop.getServiceUrl();

        // Create set of parameters needed and store in a map
        HashMap<String, String> parameters = new HashMap<String,String>();

        // Add required parameters. Change these as needed.AWSAccessKeyId、SellerId

        parameters.put("AWSAccessKeyId", shop.getShopkey()==null?"AKIAIXTHU52UC37FLJTQ":shop.getShopkey()); //shopkey
        parameters.put("Action", "ListOrders");
        parameters.put("SellerId", shop.getShopcode()==null?"AQTYEKYXJ7NPX":shop.getShopcode());//shopcode
        parameters.put("MWSAuthToken", shop.getMwsAuthToken()==null?"amzn.mws.bab0e94b-93f7-6aa7-09ad-0cc9c06694f7":shop.getMwsAuthToken());
        parameters.put("SignatureVersion","2");


        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-8);
        calendar.getTime();



        //生成时间戳
        Date d = calendar.getTime();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String str=df.format(d)+"T";
        df=new SimpleDateFormat("HH");
        String dateStr= ((Integer.parseInt(df.format(d))))+":";
        df=new SimpleDateFormat("mm:ss");
        String isoDate=str+dateStr+df.format(d)+"Z";
        parameters.put("Timestamp", urlEncode(isoDate));
        parameters.put("Version", "2013-09-01");
        parameters.put("SignatureMethod", urlEncode(ALGORITHM));

        parameters.put("LastUpdatedAfter", urlEncode("2017-01-04T16:00:00Z"));

        parameters.put("MarketplaceId.Id.1", urlEncode(shop.getVisitcode()==null?"A1F83G8C2ARO7P":shop.getVisitcode()));// visitcode


        // Format the parameters as they will appear in final format
        // (without the signature parameter)
        String formattedParameters = calculateStringToSignV2(parameters,
                serviceUrl);



        String signature =sign(formattedParameters, secretKey);

        // Add signature to the parameters and display final results
        parameters.put("Signature", urlEncode(signature));


        String url=shop.getServiceUrl()+"Orders/2013-09-01?";

        String params=calculateStringToSignV2(parameters, serviceUrl);

        int start = params.indexOf("AWSAccessKeyId");

        params=params.substring(start);

        System.out.println(url+params);

        String result=  HttpUtil.post(url+params,"");


        String json =  XMLUtil.xml2json(result);

        //System.out.println(sendGetRequest(url+params));
        return json;
    }

    public static String getFeedSubmissionList(String sessionId,Shop shop) throws Exception {
        // Change this secret key to yours
        String secretKey = shop.getSecretKey()==null?"ys/XvaP+LxVS7vXtzWnaS2CRYqmIG3HIgkMKBaBs":shop.getSecretKey();


        // Create set of parameters needed and store in a map
        HashMap<String, String> parameters = new HashMap<String,String>();

        // Add required parameters. Change these as needed.
        parameters.put("AWSAccessKeyId", shop.getShopkey()==null?"AKIAIXTHU52UC37FLJTQ":shop.getShopkey()); //shopkey
        parameters.put("Action", "GetFeedSubmissionList");
        parameters.put("SellerId", shop.getShopcode()==null?"AQTYEKYXJ7NPX":shop.getShopcode());//shopcode
        parameters.put("MWSAuthToken", shop.getMwsAuthToken()==null?"amzn.mws.bab0e94b-93f7-6aa7-09ad-0cc9c06694f7":shop.getMwsAuthToken());
        parameters.put("SignatureVersion","2");
        parameters.put("FeedSubmissionIdList.Id.1",sessionId);

        //生成时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-8);
        calendar.getTime();

        Date d = calendar.getTime();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String str=df.format(d)+"T";
        df=new SimpleDateFormat("HH");
        String dateStr= ((Integer.parseInt(df.format(d))))+":";
        df=new SimpleDateFormat("mm:ss");
        String isoDate=str+dateStr+df.format(d)+"Z";

        parameters.put("Timestamp", urlEncode(isoDate));
        parameters.put("Version", "2009-01-01");
        parameters.put("SignatureMethod", urlEncode(ALGORITHM));



        // Format the parameters as they will appear in final format
        // (without the signature parameter)
        String formattedParameters = calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);



        String signature =sign(formattedParameters, secretKey);

        // Add signature to the parameters and display final results
        parameters.put("Signature", urlEncode(signature));


        String url=SERVICE_URL+"?";

        String params=calculateStringToSignV2ForPostProduct(parameters, SERVICE_URL);

        int start = params.indexOf("AWSAccessKeyId");

        params=params.substring(start);

        System.out.println(url+params);

        String result=  HttpUtil.post(url+params,"");


        String json =  XMLUtil.xml2json(result);

        //System.out.println(sendGetRequest(url+params));
        return json;


    }

    public static String getFeedSubmissionResult(String sessionId,Shop shop) throws Exception {
        // Change this secret key to yours
        String secretKey = shop.getSecretKey()==null?"ys/XvaP+LxVS7vXtzWnaS2CRYqmIG3HIgkMKBaBs":shop.getSecretKey();


        // Create set of parameters needed and store in a map
        HashMap<String, String> parameters = new HashMap<String,String>();

        // Add required parameters. Change these as needed.
        parameters.put("AWSAccessKeyId", shop.getShopkey()==null?"AKIAIXTHU52UC37FLJTQ":shop.getShopkey()); //shopkey
        parameters.put("Action", "GetFeedSubmissionResult");
        parameters.put("SellerId", shop.getShopcode()==null?"AQTYEKYXJ7NPX":shop.getShopcode());//shopcode
        parameters.put("MWSAuthToken", shop.getMwsAuthToken()==null?"amzn.mws.bab0e94b-93f7-6aa7-09ad-0cc9c06694f7":shop.getMwsAuthToken());
        parameters.put("SignatureVersion","2");
        parameters.put("FeedSubmissionId",sessionId);

        //生成时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-8);
        calendar.getTime();

        Date d = calendar.getTime();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String str=df.format(d)+"T";
        df=new SimpleDateFormat("HH");
        String dateStr= ((Integer.parseInt(df.format(d))))+":";
        df=new SimpleDateFormat("mm:ss");
        String isoDate=str+dateStr+df.format(d)+"Z";

        parameters.put("Timestamp", urlEncode(isoDate));
        parameters.put("Version", "2009-01-01");
        parameters.put("SignatureMethod", urlEncode(ALGORITHM));



        // Format the parameters as they will appear in final format
        // (without the signature parameter)
        String formattedParameters = calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);



        String signature =sign(formattedParameters, secretKey);

        // Add signature to the parameters and display final results
        parameters.put("Signature", urlEncode(signature));


        String url=SERVICE_URL+"?";

        String params=calculateStringToSignV2ForPostProduct(parameters, SERVICE_URL);

        int start = params.indexOf("AWSAccessKeyId");

        params=params.substring(start);

        System.out.println(url+params);

        String result=  HttpUtil.post(url+params,"");


        String json =  XMLUtil.xml2json(result);

        //System.out.println(sendGetRequest(url+params));
        return json;


    }



    public static String getOrderItemList(String orderId,Shop shop) throws Exception {
        // Change this secret key to yours
        String secretKey = shop.getSecretKey()==null?"ys/XvaP+LxVS7vXtzWnaS2CRYqmIG3HIgkMKBaBs":shop.getSecretKey();

        // Use the endpoint for your marketplace
        String serviceUrl =shop.getServiceUrl()==null? "https://mws.amazonservices.co.uk/":shop.getServiceUrl();

        // Create set of parameters needed and store in a map
        HashMap<String, String> parameters = new HashMap<String,String>();

        // Add required parameters. Change these as needed.

        parameters.put("AWSAccessKeyId", shop.getShopkey()==null?"AKIAIXTHU52UC37FLJTQ":shop.getShopkey()); //shopkey
        parameters.put("Action", "ListOrders");
        parameters.put("SellerId", shop.getShopcode()==null?"AQTYEKYXJ7NPX":shop.getShopcode());//shopcode
        parameters.put("MWSAuthToken", shop.getMwsAuthToken()==null?"amzn.mws.bab0e94b-93f7-6aa7-09ad-0cc9c06694f7":shop.getMwsAuthToken());
        parameters.put("SignatureVersion","2");

        //生成时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-8);
        calendar.getTime();



        //生成时间戳
        Date d = calendar.getTime();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String str=df.format(d)+"T";
        df=new SimpleDateFormat("HH");
        String dateStr= ((Integer.parseInt(df.format(d))))+":";
        df=new SimpleDateFormat("mm:ss");
        String isoDate=str+dateStr+df.format(d)+"Z";

        parameters.put("Timestamp", urlEncode(isoDate));
        parameters.put("Version", "2013-09-01");
        parameters.put("SignatureMethod", urlEncode(ALGORITHM));

        parameters.put("LastUpdatedAfter", urlEncode("2017-01-04T16:00:00Z"));

        parameters.put("MarketplaceId.Id.1", urlEncode(shop.getVisitcode()==null?"A1F83G8C2ARO7P":shop.getVisitcode()));// visitcode

        parameters.put("AmazonOrderId", urlEncode(orderId));


        // Format the parameters as they will appear in final format
        // (without the signature parameter)
        String formattedParameters = calculateStringToSignV2(parameters,
                serviceUrl);



        String signature =sign(formattedParameters, secretKey);

        // Add signature to the parameters and display final results
        parameters.put("Signature", urlEncode(signature));


        String url="https://mws.amazonservices.co.uk/Orders/2013-09-01?";

        String params=calculateStringToSignV2(parameters,
                serviceUrl);

        int start = params.indexOf("AWSAccessKeyId");

        params=params.substring(start);

        System.out.println(url+params);

        String result=  HttpUtil.post(url+params,"");


        String json =  XMLUtil.xml2json(result);

        //System.out.println(sendGetRequest(url+params));

        return json;
    }

    public static String uploadProduct(List<Product> product, Shop shop, ShopClass shopClass, EanDao eanDao) throws Exception {
        // Change this secret key to yours
        String secretKey = shop.getSecretKey()==null?"ys/XvaP+LxVS7vXtzWnaS2CRYqmIG3HIgkMKBaBs":shop.getSecretKey();

        // Create set of parameters needed and store in a map
        HashMap<String, String> parameters = new HashMap<String,String>();

        // Add required parameters. Change these as needed.
        parameters.put("AWSAccessKeyId", shop.getShopkey()==null?"AKIAIXTHU52UC37FLJTQ":shop.getShopkey()); //shopkey
        parameters.put("Action", "SubmitFeed");
        parameters.put("SellerId", shop.getShopcode()==null?"AQTYEKYXJ7NPX":shop.getShopcode());//shopcode
        parameters.put("MWSAuthToken", shop.getMwsAuthToken()==null?"amzn.mws.bab0e94b-93f7-6aa7-09ad-0cc9c06694f7":shop.getMwsAuthToken());
        parameters.put("SignatureVersion","2");
        parameters.put("FeedType","_POST_PRODUCT_DATA_");


        //File file = new File("C://java/"+product.get(0).getSKU()+".xml");


        String path="C://java/"+product.get(0).getSKU()+".xml";
        FileOutputStream fos = new FileOutputStream(path);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");



        String content=XMLUtil.toXML(product,shop,shopClass,eanDao);

        FileWriter fw=null;
        BufferedWriter bw=null;
        try{

            osw.write(content);
            osw.flush();

            osw.close();
            fos.close();

        }catch(Exception e){
            e.printStackTrace();
        }


        //创建文件字节读取流对象时，必须明确与之关联的数据源。
        FileInputStream fis = new FileInputStream(path);
        parameters.put("ContentMD5Value",urlEncode(HttpUtil.computeContentMD5HeaderValue(fis)));

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-8);
        calendar.getTime();



        //生成时间戳
        Date d = calendar.getTime();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String str=df.format(d)+"T";
        df=new SimpleDateFormat("HH");
        String dateStr= ((Integer.parseInt(df.format(d))))+":";
        df=new SimpleDateFormat("mm:ss");
        String isoDate=str+dateStr+df.format(d)+"Z";

        parameters.put("Timestamp", urlEncode(isoDate));
        parameters.put("Version", "2013-09-01");
        parameters.put("Version", "2009-01-01");
        parameters.put("SignatureMethod", urlEncode(ALGORITHM));


        parameters.put("MarketplaceIdList.Id.1", urlEncode(shop.getVisitcode()==null?"A1F83G8C2ARO7P":shop.getVisitcode()));
        parameters.put("PurgeAndReplace", "false");
        //parameters.put("AmazonOrderId", urlEncode("203-1652646-5033144"));


        // Format the parameters as they will appear in final format
        // (without the signature parameter)
        String formattedParameters = calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);



        String signature =sign(formattedParameters, secretKey);

        // Add signature to the parameters and display final results
        parameters.put("Signature", urlEncode(signature));


        String url=SERVICE_URL+"?";

        String params=calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);

        int start = params.indexOf("AWSAccessKeyId");

        params=params.substring(start);

        System.out.println(url+params);



        byte[] bytes = new byte[0];
        bytes = new byte[fis.available()];
        fis.read(bytes);
        String xml = new String(bytes);

        String result=  HttpUtil.sendCPICPostRequest(url+params,xml);


        String json =  XMLUtil.xml2json(result);

        //System.out.println(sendGetRequest(url+params));

        return json;
    }

    public static String uploadInventory(List<Product> product,Shop shop)  throws Exception{
        // Change this secret key to yours
        String secretKey = shop.getSecretKey()==null?"ys/XvaP+LxVS7vXtzWnaS2CRYqmIG3HIgkMKBaBs":shop.getSecretKey();


        // Create set of parameters needed and store in a map
        HashMap<String, String> parameters = new HashMap<String,String>();

        // Add required parameters. Change these as needed.
        parameters.put("AWSAccessKeyId", shop.getShopkey()==null?"AKIAIXTHU52UC37FLJTQ":shop.getShopkey()); //shopkey
        parameters.put("Action", "SubmitFeed");
        parameters.put("SellerId", shop.getShopcode()==null?"AQTYEKYXJ7NPX":shop.getShopcode());//shopcode
        parameters.put("MWSAuthToken", shop.getMwsAuthToken()==null?"amzn.mws.bab0e94b-93f7-6aa7-09ad-0cc9c06694f7":shop.getMwsAuthToken());
        parameters.put("SignatureVersion","2");
        parameters.put("FeedType","_POST_INVENTORY_AVAILABILITY_DATA_");


        File file = new File("C://java/Inventory/"+product.get(0).getSKU()+".xml");


        String content=XMLUtil.toInventoryXML(product,shop);

        FileWriter fw=null;
        BufferedWriter bw=null;
        try{
            if(!file.exists()){
                file.createNewFile();
            }
            //fw=new FileWriter(file.getAbsoluteFile(),true);  //true表示可以追加新内容
            fw=new FileWriter(file.getAbsoluteFile()); //表示不追加
            bw=new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        //创建文件字节读取流对象时，必须明确与之关联的数据源。
        FileInputStream fis = new FileInputStream(file);
        parameters.put("ContentMD5Value",urlEncode(HttpUtil.computeContentMD5HeaderValue(fis)));

        //生成时间戳

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-8);

        Date d = calendar.getTime();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String str=df.format(d)+"T";
        df=new SimpleDateFormat("HH");
        String dateStr= ((Integer.parseInt(df.format(d))))+":";
        df=new SimpleDateFormat("mm:ss");
        String isoDate=str+dateStr+df.format(d)+"Z";

        //parameters.put("Timestamp", urlEncode(isoDate));

        parameters.put("Timestamp", urlEncode(isoDate));
        parameters.put("Version", "2009-01-01");
        parameters.put("SignatureMethod", urlEncode(ALGORITHM));


        parameters.put("MarketplaceIdList.Id.1", urlEncode(shop.getVisitcode()==null?"A1F83G8C2ARO7P":shop.getVisitcode()));
        parameters.put("PurgeAndReplace", "false");

        //parameters.put("AmazonOrderId", urlEncode("203-1652646-5033144"));


        // Format the parameters as they will appear in final format
        // (without the signature parameter)
        String formattedParameters = calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);



        String signature =sign(formattedParameters, secretKey);

        // Add signature to the parameters and display final results
        parameters.put("Signature", urlEncode(signature));


        String url=SERVICE_URL+"?";

        String params=calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);

        int start = params.indexOf("AWSAccessKeyId");

        params=params.substring(start);

        System.out.println(url+params);



        byte[] bytes = new byte[0];
        bytes = new byte[fis.available()];
        fis.read(bytes);
        String xml = new String(bytes);

        String result=  HttpUtil.sendCPICPostRequest(url+params,xml);


        String json =  XMLUtil.xml2json(result);

        //System.out.println(sendGetRequest(url+params));

        return json;
    }

    public static String uploadPrice(List<Product> product,Shop shop)  throws Exception{
        // Change this secret key to yours
        String secretKey = shop.getSecretKey()==null?"ys/XvaP+LxVS7vXtzWnaS2CRYqmIG3HIgkMKBaBs":shop.getSecretKey();


        // Create set of parameters needed and store in a map
        HashMap<String, String> parameters = new HashMap<String,String>();

        // Add required parameters. Change these as needed.
        parameters.put("AWSAccessKeyId", shop.getShopkey()==null?"AKIAIXTHU52UC37FLJTQ":shop.getShopkey()); //shopkey
        parameters.put("Action", "SubmitFeed");
        parameters.put("SellerId", shop.getShopcode()==null?"AQTYEKYXJ7NPX":shop.getShopcode());//shopcode
        parameters.put("MWSAuthToken", shop.getMwsAuthToken()==null?"amzn.mws.bab0e94b-93f7-6aa7-09ad-0cc9c06694f7":shop.getMwsAuthToken());
        parameters.put("SignatureVersion","2");
        parameters.put("FeedType","_POST_PRODUCT_PRICING_DATA_");


        File file = new File("C://java/Price/"+product.get(0).getSKU()+".xml");


        String content=XMLUtil.toPriceXML(product,shop);

        FileWriter fw=null;
        BufferedWriter bw=null;
        try{
            if(!file.exists()){
                file.createNewFile();
            }
            //fw=new FileWriter(file.getAbsoluteFile(),true);  //true表示可以追加新内容
            fw=new FileWriter(file.getAbsoluteFile()); //表示不追加
            bw=new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        //创建文件字节读取流对象时，必须明确与之关联的数据源。
        FileInputStream fis = new FileInputStream(file);
        parameters.put("ContentMD5Value",urlEncode(HttpUtil.computeContentMD5HeaderValue(fis)));

        //生成时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-8);
        calendar.getTime();

        Date d = calendar.getTime();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String str=df.format(d)+"T";
        df=new SimpleDateFormat("HH");
        String dateStr= ((Integer.parseInt(df.format(d))))+":";
        df=new SimpleDateFormat("mm:ss");
        String isoDate=str+dateStr+df.format(d)+"Z";

        parameters.put("Timestamp", urlEncode(isoDate));
        parameters.put("Version", "2009-01-01");
        parameters.put("SignatureMethod", urlEncode(ALGORITHM));


        parameters.put("MarketplaceIdList.Id.1", urlEncode(shop.getVisitcode()==null?"A1F83G8C2ARO7P":shop.getVisitcode()));
        parameters.put("PurgeAndReplace", "false");

        //parameters.put("AmazonOrderId", urlEncode("203-1652646-5033144"));


        // Format the parameters as they will appear in final format
        // (without the signature parameter)
        String formattedParameters = calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);



        String signature =sign(formattedParameters, secretKey);

        // Add signature to the parameters and display final results
        parameters.put("Signature", urlEncode(signature));


        String url=SERVICE_URL+"?";

        String params=calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);

        int start = params.indexOf("AWSAccessKeyId");

        params=params.substring(start);

        System.out.println(url+params);



        byte[] bytes = new byte[0];
        bytes = new byte[fis.available()];
        fis.read(bytes);
        String xml = new String(bytes);

        String result=  HttpUtil.sendCPICPostRequest(url+params,xml);


        String json =  XMLUtil.xml2json(result);

        //System.out.println(sendGetRequest(url+params));

        return json;
    }

    public static String uploadImage(List<Product> product,Shop shop)  throws Exception{
        // Change this secret key to yours
        String secretKey = shop.getSecretKey()==null?"ys/XvaP+LxVS7vXtzWnaS2CRYqmIG3HIgkMKBaBs":shop.getSecretKey();


        // Create set of parameters needed and store in a map
        HashMap<String, String> parameters = new HashMap<String,String>();

        // Add required parameters. Change these as needed.
        parameters.put("AWSAccessKeyId", shop.getShopkey()==null?"AKIAIXTHU52UC37FLJTQ":shop.getShopkey()); //shopkey
        parameters.put("Action", "SubmitFeed");
        parameters.put("SellerId", shop.getShopcode()==null?"AQTYEKYXJ7NPX":shop.getShopcode());//shopcode
        parameters.put("MWSAuthToken", shop.getMwsAuthToken()==null?"amzn.mws.bab0e94b-93f7-6aa7-09ad-0cc9c06694f7":shop.getMwsAuthToken());
        parameters.put("SignatureVersion","2");
        parameters.put("FeedType","_POST_PRODUCT_IMAGE_DATA_");


        File file = new File("C://java/Image/"+product.get(0).getSKU()+".xml");


        String content=XMLUtil.toImageXML(product,shop);

        FileWriter fw=null;
        BufferedWriter bw=null;
        try{
            if(!file.exists()){
                file.createNewFile();
            }
            //fw=new FileWriter(file.getAbsoluteFile(),true);  //true表示可以追加新内容
            fw=new FileWriter(file.getAbsoluteFile()); //表示不追加
            bw=new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        //创建文件字节读取流对象时，必须明确与之关联的数据源。
        FileInputStream fis = new FileInputStream(file);
        parameters.put("ContentMD5Value",urlEncode(HttpUtil.computeContentMD5HeaderValue(fis)));

        //生成时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-8);
        calendar.getTime();



        //生成时间戳
        Date d = calendar.getTime();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String str=df.format(d)+"T";
        df=new SimpleDateFormat("HH");
        String dateStr= ((Integer.parseInt(df.format(d))))+":";
        df=new SimpleDateFormat("mm:ss");
        String isoDate=str+dateStr+df.format(d)+"Z";

        parameters.put("Timestamp", urlEncode(isoDate));
        parameters.put("Version", "2009-01-01");
        parameters.put("SignatureMethod", urlEncode(ALGORITHM));


        parameters.put("MarketplaceIdList.Id.1", urlEncode(shop.getVisitcode()==null?"A1F83G8C2ARO7P":shop.getVisitcode()));
        parameters.put("PurgeAndReplace", "false");

        //parameters.put("AmazonOrderId", urlEncode("203-1652646-5033144"));


        // Format the parameters as they will appear in final format
        // (without the signature parameter)
        String formattedParameters = calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);



        String signature =sign(formattedParameters, secretKey);

        // Add signature to the parameters and display final results
        parameters.put("Signature", urlEncode(signature));


        String url=SERVICE_URL+"?";

        String params=calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);

        int start = params.indexOf("AWSAccessKeyId");

        params=params.substring(start);

        System.out.println(url+params);



        byte[] bytes = new byte[0];
        bytes = new byte[fis.available()];
        fis.read(bytes);
        String xml = new String(bytes);

        String result=  HttpUtil.sendCPICPostRequest(url+params,xml);


        String json =  XMLUtil.xml2json(result);

        //System.out.println(sendGetRequest(url+params));

        return json;
    }


    public static String uploadVariation(List<Product> product,Shop shop)  throws Exception{
        // Change this secret key to yours
        String secretKey = shop.getSecretKey()==null?"ys/XvaP+LxVS7vXtzWnaS2CRYqmIG3HIgkMKBaBs":shop.getSecretKey();


        // Create set of parameters needed and store in a map
        HashMap<String, String> parameters = new HashMap<String,String>();

        // Add required parameters. Change these as needed.
        parameters.put("AWSAccessKeyId", shop.getShopkey()==null?"AKIAIXTHU52UC37FLJTQ":shop.getShopkey()); //shopkey
        parameters.put("Action", "SubmitFeed");
        parameters.put("SellerId", shop.getShopcode()==null?"AQTYEKYXJ7NPX":shop.getShopcode());//shopcode
        parameters.put("MWSAuthToken", shop.getMwsAuthToken()==null?"amzn.mws.bab0e94b-93f7-6aa7-09ad-0cc9c06694f7":shop.getMwsAuthToken());
        parameters.put("SignatureVersion","2");
        parameters.put("FeedType","_POST_PRODUCT_RELATIONSHIP_DATA_");


        File file = new File("C://java/Variation/"+product.get(0).getSKU()+".xml");


        String content=XMLUtil.toVariationXML(product,shop);

        FileWriter fw=null;
        BufferedWriter bw=null;
        try{
            if(!file.exists()){
                file.createNewFile();
            }
            //fw=new FileWriter(file.getAbsoluteFile(),true);  //true表示可以追加新内容
            fw=new FileWriter(file.getAbsoluteFile()); //表示不追加
            bw=new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        //创建文件字节读取流对象时，必须明确与之关联的数据源。
        FileInputStream fis = new FileInputStream(file);
        parameters.put("ContentMD5Value",urlEncode(HttpUtil.computeContentMD5HeaderValue(fis)));

        //生成时间戳
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR,-8);
        calendar.getTime();



        //生成时间戳
        Date d = calendar.getTime();
        DateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String str=df.format(d)+"T";
        df=new SimpleDateFormat("HH");
        String dateStr= ((Integer.parseInt(df.format(d))))+":";
        df=new SimpleDateFormat("mm:ss");
        String isoDate=str+dateStr+df.format(d)+"Z";

        parameters.put("Timestamp", urlEncode(isoDate));
        parameters.put("Version", "2009-01-01");
        parameters.put("SignatureMethod", urlEncode(ALGORITHM));


        parameters.put("MarketplaceIdList.Id.1", urlEncode(shop.getVisitcode()==null?"A1F83G8C2ARO7P":shop.getVisitcode()));
        parameters.put("PurgeAndReplace", "false");

        //parameters.put("AmazonOrderId", urlEncode("203-1652646-5033144"));


        // Format the parameters as they will appear in final format
        // (without the signature parameter)
        String formattedParameters = calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);



        String signature =sign(formattedParameters, secretKey);

        // Add signature to the parameters and display final results
        parameters.put("Signature", urlEncode(signature));


        String url=SERVICE_URL+"?";

        String params=calculateStringToSignV2ForPostProduct(parameters,
                SERVICE_URL);

        int start = params.indexOf("AWSAccessKeyId");

        params=params.substring(start);

        System.out.println(url+params);



        byte[] bytes = new byte[0];
        bytes = new byte[fis.available()];
        fis.read(bytes);
        String xml = new String(bytes);

        String result=  HttpUtil.sendCPICPostRequest(url+params,xml);


        String json =  XMLUtil.xml2json(result);

        //System.out.println(sendGetRequest(url+params));

        return json;
    }





















    /* If Signature Version is 2, string to sign is based on following:
    *
    *    1. The HTTP Request Method followed by an ASCII newline (%0A)
    *
    *    2. The HTTP Host header in the form of lowercase host,
    *       followed by an ASCII newline.
    *
    *    3. The URL encoded HTTP absolute path component of the URI
    *       (up to but not including the query string parameters);
    *       if this is empty use a forward '/'. This parameter is followed
    *       by an ASCII newline.
    *
    *    4. The concatenation of all query string components (names and
    *       values) as UTF-8 characters which are URL encoded as per RFC
    *       3986 (hex characters MUST be uppercase), sorted using
    *       lexicographic byte ordering. Parameter names are separated from
    *       their values by the '=' character (ASCII character 61), even if
    *       the value is empty. Pairs of parameter and values are separated
    *       by the '&' character (ASCII code 38).
    *
    */
    public static String calculateStringToSignV2(
            Map<String, String> parameters, String serviceUrl)
            throws SignatureException, URISyntaxException {
        // Sort the parameters alphabetically by storing
        // in TreeMap structure
        Map<String, String> sorted = new TreeMap<String, String>();
        sorted.putAll(parameters);

        // Set endpoint value
        URI endpoint = new URI(serviceUrl.toLowerCase());

        // Create flattened (String) representation
        StringBuilder data = new StringBuilder();
        data.append("POST\n");
        data.append(endpoint.getHost());
        //data.append("\n");
        //data.append("/Orders/2013-09-01");
        data.append("\n/Orders/2013-09-01");
        data.append("\n");

        Iterator<Entry<String, String>> pairs =
                sorted.entrySet().iterator();
        while (pairs.hasNext()) {
            Entry<String, String> pair = pairs.next();
            if (pair.getValue() != null) {
                data.append( pair.getKey() + "=" + pair.getValue());
            }
            else {
                data.append( pair.getKey() + "=");
            }

            // Delimit parameters with ampersand (&)
            if (pairs.hasNext()) {
                data.append( "&");
            }
        }

        //System.out.println(data.toString());
        return data.toString();
    }


    public static String calculateStringToSignV2ForPostProduct(
            Map<String, String> parameters, String serviceUrl)
            throws SignatureException, URISyntaxException {
        // Sort the parameters alphabetically by storing
        // in TreeMap structure
        Map<String, String> sorted = new TreeMap<String, String>();
        sorted.putAll(parameters);

        // Set endpoint value
        URI endpoint = new URI(serviceUrl.toLowerCase());

        // Create flattened (String) representation
        StringBuilder data = new StringBuilder();
        data.append("POST\n");
        data.append(endpoint.getHost());
        //data.append("\n");
        //data.append("/Orders/2013-09-01");
        data.append("\n/");
        data.append("\n");

        Iterator<Entry<String, String>> pairs =
                sorted.entrySet().iterator();
        while (pairs.hasNext()) {
            Entry<String, String> pair = pairs.next();
            if (pair.getValue() != null) {
                data.append( pair.getKey() + "=" + pair.getValue());
            }
            else {
                data.append( pair.getKey() + "=");
            }

            // Delimit parameters with ampersand (&)
            if (pairs.hasNext()) {
                data.append( "&");
            }
        }

        //System.out.println(data.toString());
        return data.toString();
    }

    /*
     * Sign the text with the given secret key and convert to base64
     */
    public static String sign(String data, String secretKey)
            throws NoSuchAlgorithmException, InvalidKeyException,
            IllegalStateException, UnsupportedEncodingException {
        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(new SecretKeySpec(secretKey.getBytes(CHARACTER_ENCODING),
                ALGORITHM));
        byte[] signature = mac.doFinal(data.getBytes(CHARACTER_ENCODING));
        String signatureBase64 = new String(Base64.encodeBase64(signature) ,
                CHARACTER_ENCODING);


        return new String(signatureBase64);
    }

    public static String urlEncode(String rawValue) {
        String value = (rawValue == null) ? "" : rawValue;
        String encoded = null;

        try {
            encoded = URLEncoder.encode(value, CHARACTER_ENCODING)
                    .replace("+", "%20")
                    .replace("*", "%2A")
                    .replace("%7E","~");
        } catch (UnsupportedEncodingException e) {
            System.err.println("Unknown encoding: " + CHARACTER_ENCODING);
            e.printStackTrace();
        }

        return encoded;
    }


    public static String sendGetRequest(String getUrl)
    {
        StringBuffer sb = new StringBuffer();
        InputStreamReader isr = null;
        BufferedReader br = null;
        try
        {
            URL url = new URL(getUrl);
            URLConnection urlConnection = url.openConnection();
            urlConnection.setAllowUserInteraction(false);
            isr = new InputStreamReader(url.openStream());
            br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null)
            {
                sb.append(line);
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            //fileOperator.closeResources(isr, br);
        }
        return sb.toString();
    }


}



